package com.machine.dao.user.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.machine.bean.BuyComponent;
import com.machine.bean.Componentpart;
import com.machine.dao.user.BuyComponentDao;

@Component(value = "buyComponentDao")
@Transactional
public class BuyComponentDaoImpl implements BuyComponentDao {

	private SessionFactory sessionfactory;

	public SessionFactory getSessionfactory() {
		return sessionfactory;
	}

	@Resource
	public void setSessionfactory(SessionFactory sessionfactory) {
		this.sessionfactory = sessionfactory;
	}

	@Override
	public int addBuyCom(BuyComponent buyComponent) {
		return (Integer) sessionfactory.getCurrentSession().save(buyComponent);
	}

	@Override
	public int getAllRowCount(String hql) {
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		List list = query.list();
		System.out.println("cout : " + list.size());
		return list.size();
	}

	@Override
	public List queryForPage(String hql, int offset, int length) {
		Session session = sessionfactory.getCurrentSession();
		Query query = session.createQuery(hql);
		query.setFirstResult(offset);
		query.setMaxResults(length);
		List list = query.list();
		return list;
	}

	@Override
	public int deleteByIdList(List<Integer> idList) {
		BuyComponent buyComponent = null;
		for (Integer id : idList) {
			buyComponent = new BuyComponent();
			buyComponent.setId(id);
			sessionfactory.getCurrentSession().delete(buyComponent);
		}
		return 1;
	}

	@Override
	public BuyComponent findById(Integer id) {
		String hql = "from BuyComponent buycomponent where buycomponent.id ="
			+ id + " ";
	Session session = sessionfactory.getCurrentSession();
	Query query = session.createQuery(hql);
	List<BuyComponent> comList = query.list();
	if (comList.size() > 0) {
		return comList.get(0);
	}
	return null;
	}

	@Override
	public int update(BuyComponent buyComponent) {
		sessionfactory.getCurrentSession().update(buyComponent);
		return 1;
	}

}
